/*
 * console.c
 *
 *  Created on: Dec 18, 2010
 *      Author: cumeo89
 */

#include <stdlib.h>
#include <stdio.h>
#include <glib.h>
#include "lcsfile.h"
#include "lcstr.h"

#define MAX_LENGTH 2*1024*1024 /* 2MB string */
#define MAX_STRING_COUNT 20 /* 20 strings */

char *readString(const char *path) {
	FILE *f = fopen(path, "rt");
	char *s = (char *)malloc(MAX_LENGTH);
	fread(s, 1, MAX_LENGTH, f);
	fclose(f);
	return s;
}

int lcsfile_run(const char **paths) {
	char *strings[MAX_STRING_COUNT+1];
	int i, k;
	for (k = 0; paths[k] != NULL && k < MAX_STRING_COUNT; k++) {
		strings[k] = readString(paths[k]);
	}
	strings[k] = NULL;
	if (k < 2) {
		printf("Provide at least 2 text files.");
		return 0;
	}
	if (paths[k] != NULL) {
		printf("Max number of strings is %d, the rest is rejected.", MAX_STRING_COUNT);
	}

	CommonString *commonStrings = find_lcstr((const char **)strings);
	for (i = 0; i < k-1; i++) {
		printf("--- Longest common string between at least %d strings: ---\n", i+2);
		printf("Length: %d\n", commonStrings[i].length);
		printf("Content: %s\n\n", cs_get_substring(&commonStrings[i]));
	}

	cs_free(commonStrings, k);
	for (i = 0; i < k; i++) {
		free(strings[i]);
	}

	return 0;
}
